const viewerId = "dmap"
const rightViewerId = "leftDmap"
export { viewerId, rightViewerId }

export function initSelectedStateIcon (viewer) {
  // 默认选中图标不可见
  const selectedIcon = new DE.Billboard("0, 0", "./img/marker/selected.png")
  mountToWindow({ selectedIcon })
  selectedIcon._hasEdit = false
  selectedIcon.size = [40, 40]
  selectedIcon.show = false
  const selectedIconLayer = new DE.VectorLayer("selectedIconLayer")
  viewer && viewer.addLayer(selectedIconLayer)
  selectedIconLayer && selectedIconLayer.addOverlay(selectedIcon)
}

/**
 * 将部分方法绑定为 window 全局方法
 * @param options
 */
export function mountToWindow (options = {}) {
  Object.keys(options).forEach((k) => {
    window[`$${k}`] = options[k]
  })
}


/**
 * 二三维联动
 */

let worldPosition, distance

const syncAnotherViewerView = (mainViewer, childViewer) => {
  if (!mainViewer || !childViewer) {
    return false
  }
  try {
    const Cesium = DE.__namespace.Cesium
    const x = Math.floor(mainViewer.canvas.clientWidth / 2)
    const y = Math.floor(mainViewer.canvas.clientHeight / 2)
    const viewerCenter = new Cesium.Cartesian2(x, y)
    const newWorldPosition = mainViewer.scene.camera.pickEllipsoid(viewerCenter)
    if (Cesium.defined(newWorldPosition)) {
      worldPosition = newWorldPosition
    }
    distance = Cesium.Cartesian3.distance(worldPosition, mainViewer.scene.camera.positionWC)
    childViewer?.scene?.camera?.lookAt(worldPosition, new Cesium.Cartesian3(0.0, 0.0, distance))
  } catch (e) {
    console.error(e)
  }
}

/**
 * 两个球视角绑定
 * @param {DE.Viewer} mainViewer
 * @param {DE.Viewer} childViewer
 * @param {Function} context
 */
export function syncViewer (mainViewer, childViewer, context) {
  if (!mainViewer || !childViewer) {
    return false
  }
  childViewer.setOptions({
    cameraController: {
      enableInputs: false
    }
  })
  mainViewer.camera.changed.addEventListener(syncAnotherViewerView.bind(context, mainViewer, childViewer))
  mainViewer.camera.percentageChanged = 0.01
  childViewer.scene.screenSpaceCameraController.enableRotate = false
  childViewer.scene.screenSpaceCameraController.enableTranslate = false
  childViewer.scene.screenSpaceCameraController.enableZoom = false
  childViewer.scene.screenSpaceCameraController.enableLook = false
  childViewer.scene.screenSpaceCameraController.enableTilt = false
}

/**
 * 两个球相机事件解绑
 * @param mainViewer
 */
export function unsyncViewer (mainViewer) {
  mainViewer.camera.changed.removeEventListener(syncAnotherViewerView)
}
